package org.mozhu.mysql.learning.hitcounter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service("DBHitCounterService")
public class DBHitCounterService implements HitCounterService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void increase() {
        jdbcTemplate.update("UPDATE hit_counter SET cnt = cnt + 1");
    }

    @Override
    public int count() {
        return jdbcTemplate.queryForObject("select cnt from hit_counter", Integer.class);
    }

    @Override
    public void reset() {
        int cnt = jdbcTemplate.update("UPDATE hit_counter SET cnt = 0");
        if (cnt == 0) {
            jdbcTemplate.update("INSERT INTO hit_counter (cnt) values(0)");
        }
    }
}
